package serializable.writable;


import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.serializer.WritableSerialization;

import java.io.*;


public class MyWritable implements Writable, Serializable {
    private int counter;
    private long timestamp;

    public static void main(String[] args) throws IOException {

        MyWritable mywrite = new MyWritable();
        mywrite.setCounter(1234);
        mywrite.setTimestamp(1568323838);
        IntWritable intw = new IntWritable();

        byte[] sss = serizlize(mywrite);
        System.out.println(serizlize(mywrite).toString());
    }

    @Override
    public void write(DataOutput dataOutput) throws IOException {
        //写入到DataOutput二进制流中
        dataOutput.writeInt(counter);
        dataOutput.writeLong(timestamp);
    }

    @Override
    public void readFields(DataInput dataInput) throws IOException {
        //从DataInput 数据流中读取值
        this.counter = dataInput.readInt();
        this.timestamp = dataInput.readLong();
    }

    public static MyWritable read(DataInput in) throws IOException {
        MyWritable w = new MyWritable();
        w.readFields(in);
        return w;
    }

    public int getCounter() {
        return counter;
    }

    public void setCounter(int counter) {
        this.counter = counter;
    }

    public long getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(long timestamp) {
        this.timestamp = timestamp;
    }

    public static byte[] serizlize(Writable writable) throws IOException {

        //创建一个输出字节流对象
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DataOutputStream dataout = new DataOutputStream(out);

        //将结构化数据的对象writable写入到输出字节流。
        writable.write(dataout);
        return out.toByteArray();
    }


    public static byte[] deserizlize(Writable writable, byte[] bytes) throws IOException {

        //创建一个输入字节流对象，将字节数组中的数据，写入到输入流中
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        DataInputStream datain = new DataInputStream(in);

        //将输入流中的字节流数据反序列化
        writable.readFields(datain);
        return bytes;

    }
}
